package com.zhuqi.task;

import cn.hutool.core.util.StrUtil;
import com.zhuqi.service.session.Session;
import com.zhuqi.session.user.UserSession;
import com.zhuqi.util.ParamConst;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>类描述</p>
 * @author zhuqi
 * @since 2023/3/10 17:02
 */
@Component
@Slf4j
public class ExpiredDeleteTask {

	@Resource
	private Session session;

	@Resource
	private StringRedisTemplate stringRedisTemplate;

	@PostConstruct
	private void initExpireTime() {

	}

	/**
	 * 因为有闲时心跳 + 续约
	 * 不再主动删除会话
	 */
	@Scheduled(cron = "* 0/15 * * * ? ")
	public void expiredDeleteTaskMethod() {
		log.info("开始删除过期session");
		// 先处理下不活跃的Channel
		session.safeDelete();

		Map<Channel, List<UserSession>> channelUserSessionMap = session.getChannelUserSessionMap();
		Set<Channel> channels = channelUserSessionMap.keySet();
		for (Channel channel : channels) {
			if (!channel.isActive()) {
				channel.close();
				continue;
			}
			String value = stringRedisTemplate.opsForValue()
					.get(ParamConst.SESSION_KEY + channel.remoteAddress().toString());
			if (StrUtil.isBlank(value)) {
				ChannelFuture close = channel.close();
				close.addListener((ChannelFutureListener) future -> {
					log.info("");
				});
			}
		}


	}
}
